import asyncio

class EMA_Chicken:
  def __init__(self, logger, pair, candle, lot, limit_rate):
    self._logger = logger
    self._pair   = pair
    self._candle = candle

    self._remain = 0
    self._total  = 0

    self._lot        = lot
    self._limit_rate = limit_rate

    self._total = 0

    asyncio.create_task(self._main())

  async def _main(self):
    self._logger.info("started")
    while True:
      await self._pair.ticker.wait()
      if len(self._candle.values) == 0:
        continue

      price = self._pair.ticker.price
      ema   = self._candle.EMA(200)

      if price > ema:
        if self._remain < self._lot*3:
          buy = await self._pair.buy_market(self._lot)
          await asyncio.sleep(0.5)
          await buy.update()
          outgo = buy.price * self._lot
          self._total  -= outgo
          self._remain += self._lot
          self._logger.info(f"<BUY> {self._lot} / {outgo} ({self._remain} / {self._total})")

          limit_price = buy.price*(1+self._limit_rate)
          stop_price  = buy.price*(1-self._limit_rate)
          sell = await self._pair.sell_limit(self._lot, limit_price)
          while True:
            await asyncio.sleep(0.5)
            await sell.update()

            if sell.done:
              amount = sell.amount - sell.remain
              income = sell.price * amount
              self._total  += income
              self._remain -= amount
              if amount > 0:
                self._logger.info(f"[WIN] <SELL> {amount} / {income} ({self._remain} / {self._total})")
              break

            if self._pair.ticker.price < stop_price:
              await sell.cancel()
              sell = await self._pair.sell_market(self._lot)
              await asyncio.sleep(0.5)
              await sell.update()
              amount = sell.amount
              income = sell.price * sell.amount
              self._total  += income
              self._remain -= amount
              if amount > 0:
                self._logger.info(f"[LOSE] <SELL> {amount} / {income} ({self._remain} / {self._total})")
              break
